<template>
  <div class="detail-container">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      label-width="100px"
      label-suffix=":"
    >

      <sticky :z-index="10" :class-name="'sub-navbar ' + postForm.color">
        <el-button v-loading="loading" type="success" @click="submitForm">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </sticky>

      <div class="app-container" style="padding: 10px 20px">
        <warn />

        <el-row>
          <el-col :span="24">
            <el-form-item label="下单时间">
              <el-date-picker
                class="filter-item"
                v-model="postForm.date"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="开始日期">
              </el-date-picker>
            </el-form-item>

            <!--<el-form-item label="是否支付">-->
            <!--  <el-select-->
            <!--    v-model="postForm.pay"-->
            <!--    clearable-->
            <!--    filterable-->
            <!--    class="filter-item"-->
            <!--    style="width: 300px"-->
            <!--  >-->
            <!--    <el-option-->
            <!--      v-for="item in [{ value: 0, label: '未支付'}, { value: 1, label: '已支付' }]"-->
            <!--      :label="item.label"-->
            <!--      :key="item.value"-->
            <!--      :value="item.value"-->
            <!--    />-->
            <!--  </el-select>-->
            <!--  <p>请选择是否支付</p>-->
            <!--</el-form-item>-->

            <el-form-item label="会员电话">
              <el-input v-model.trim="user.mobile" disabled style="width: 300px" />
            </el-form-item>
            <el-form-item label="会员城市">
              <el-input disabled v-model="user.city" />
            </el-form-item>
            <el-form-item label="会员地址">
              <el-input type="textarea" disabled v-model="user.address" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-for="(l, i) in line" :key="i">
          <el-col :span="6">
            <el-form-item label="商品">
              <el-select
                v-model="l.product"
                clearable
                filterable
                class="filter-item"
                style="width: 300px"
                @change="changeProduct(l)"
              >
                <el-option
                  v-for="item in products"
                  :label="item.sn + '-' + item.title"
                  :key="item.id"
                  :value="item.id"
                />
              </el-select>
              <p>可以编码或者产品名称搜索</p>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="规格">
              <el-select
                v-model="l.sku"
                clearable
                filterable
                class="filter-item"
                style="width: 300px"
                @change="changeSku(l)"
              >
                <el-option
                  v-for="item in l.sku_list"
                  :label="item.names"
                  :key="item.id"
                  :value="item.id"
                />
              </el-select>
              <p>先选择产品</p>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="数量">
              <el-input v-model.trim="l.quantity" style="width: 100px" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="价格">
              <el-input v-model.trim="l.price" style="width: 100px" />
              <p>这里可以改单价</p>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="小计">
              <el-input disabled :value="(l.price * l.quantity).toFixed(2)" style="width: 100px" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <!--<el-button type="danger" @click="del(i)">删除({{l.id}})</el-button>-->
            <el-button type="danger" @click="del(i)">删除</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :offset="2">
            <el-button
              type="primary"
              icon="el-icon-circle-plus-outline"
              class="filter-item"
              size="small"
              @click="add"
            >继续添加</el-button>
          </el-col>
          <el-col :offset="6">
            <span style="color:red;">总计: {{ total }}</span>
          </el-col>
        </el-row>
      </div>

    </el-form>
  </div>
</template>

<script>
import api from '@/api'
import Sticky from '@/components/Sticky'
import Warn from './Warn'
export default {
  name: 'BaoDetail',
  components: {
    Sticky,
    Warn
  },
  props: {
    /**
     * 是否为编辑
     */
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    total() {
      let sum = 0
      this.line.forEach(x => {
        sum += x.price * x.quantity
      })
      return sum.toFixed(2)
    }
  },
  data() {
    const quantityValidate = (rule, value, callback) => {
      if (value === undefined || value.length <= 0 || Number.isNaN(+value) || +value <= 0) {
        callback(new Error('数量错误'))
      } else {
        callback()
      }
    }

    return {
      id: -1,
      user: {},
      // 商品列表
      products: [],
      loading: false,
      postForm: {
        color: 'draft',
        quantity: 1
      },
      line: [
        {
          id: 1,
          product: null,
          quantity: 1,
          price: 0,
          sku_list: []
        }
      ],
      rules: {
        quantity: [{ validator: quantityValidate, trigger: 'blur' }],
        product: [{ message: '请选择商品', trigger: 'change', required: true }]
      }
    }
  },
  created() {
    this.id = this.$route.params.id
    this.getUser()
    this.getProducts()
  },
  methods: {
    changeSku(l) {
      this.line.forEach(x => {
        if (x.id === l.id && x.product === l.product) {
          x.sku_list.forEach(y => {
            if (+y.id === +x.sku) {
              this.$set(l, 'price', y.price)
              this.$set(l, 'sku_name', y.names.split(',').filter(x => x.length > 0))
            }
          })
        }
      })
    },
    changeProduct(l) {
      // console.log(p)
      api.member.baoSku({ id: l.product }).then(response => {
        const { data } = response
        // this.sku = data.list
        // console.log(this.sku)
        // 取消规格
        this.line.forEach(x => {
          if (x.id === l.id && x.product === l.product) {
            this.$set(x, 'sku', null)
            this.$set(x, 'sku_list', data.list)
          }
        })
        this.products.forEach(x => {
          if (+x.id === +l.product) {
            this.$set(l, 'price', x.price)
          }
        })
      })
    },
    add() {
      let id = 1
      if (this.line.length > 0) {
        id = this.line[this.line.length - 1].id + 1
      }
      this.line.push({
        product: null,
        quantity: 1,
        sku_list: [],
        // 是否支付
        pay: 0,
        id
      })
    },
    del(i) {
      this.line.splice(i, 1)
    },
    getUser() {
      api.member.baoUser({ id: this.id }).then(response => {
        const { data } = response
        this.user = data.user
      })
    },
    getProducts() {
      api.member.baoProduct().then(response => {
        const { data } = response
        this.products = data.list
        // 编辑没有定义
        this.products.forEach(x => {
          if (!x.sn) {
            this.$set(x, 'sn', '')
          }
        })
      })
    },
    /**
     * 获取编辑数据
     */
    // async fetchData(id) {
    //   const response = await api.order.baoFetch({ id })
    //   this.postForm = Object.assign({}, response.data)
    // },
    /**
     * 提交表单
     */
    submitForm() {
      this.line.forEach(x => {
        // 把SKU值改成数组, 对应数据库
        if (x.sku) {
          this.$set(x, 'sku_value', [x.sku])
        }
      })
      const list = this.line.filter(x => x.product && x.quantity > 0)
      console.log(list)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          api.member.baoSave({
            id: this.id,
            ...this.postForm,
            list
          }).then(response => {
            this.loading = false
            this.$notify({
              title: '成功',
              message: response.message || '操作成功',
              type: 'success',
              duration: 2000
            })
            // this.$router.push(`/order/bao-edit/${response.data.id}`)
            // this.$router.push('/order/list')
            this.$router.push('/marketing/order')
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },

  }
}
</script>

<style scoped lang="scss">
.detail-container {
  //
}
</style>
